<?php
namespace app\controller;

use app\BaseController;
use think\facade\Request;
use think\facade\Db;
use think\Exception;


class PurchaseBill extends BaseController
{
    //获取所有基础资料信息
    public function Get_BasicsInfo()
    {
        $userId = $this->request->auth['data']->user->user_id;
        $userRoot = $this->request->auth['data']->user->user_root;

        // 根据用户ID获取公司ID
        $companyId = Db::name('user')->where('user_id', $userId)->value('user_company_id');

        $data=[];
        try{
            if($userRoot==1){
                $data['branch']=Db::table('branch')->where('branch_company_id', $companyId)->select();
            }else{
                $data['branch']=Db::table('vw_user_branch')->where('user_id', $userId)->select();

            }
            $data['supplier']=Db::table('supplier')->where('supplier_company_id', $companyId)->where('supplier_switch', 1)->select();
            $data['goodcategory']=Db::table('SET_GoodsCategory')->where('GoodsCategory_company_id', $companyId)->where('GoodsCategory_switch', 1)->select();
            $data['goodsbrand']=Db::table('SET_GoodsBrand')->where('GoodsBrand_company_id', $companyId)->where('GoodsBrand_switch', 1)->select();
            $data['goodsgrade']=Db::table('SET_GoodsGrade')->where('GoodsGrade_company_id', $companyId)->where('GoodsGrade_switch', 1)->select();
            $data['goodsseries']=Db::table('SET_GoodsSeries')->where('GoodsSeries_company_id', $companyId)->where('GoodsSeries_switch', 1)->select();
            $data['stoneinlay']=Db::table('SET_StoneInlay')->where('StoneInlay_company_id', $companyId)->where('StoneInlay_switch', 1)->select();
            $data['stonecategory']=Db::table('SET_StoneCategory')->where('StoneCategory_company_id', $companyId)->where('StoneCategory_switch', 1)->select();
            $data['stoneclarity']=Db::table('SET_StoneClarity')->where('StoneClarity_company_id', $companyId)->where('StoneClarity_switch', 1)->select();
            $data['stonecolor']=Db::table('SET_StoneColor')->where('StoneColor_company_id', $companyId)->where('StoneColor_switch', 1)->select();
            $data['stonecut']=Db::table('SET_StoneCut')->where('StoneCut_company_id', $companyId)->where('StoneCut_switch', 1)->select();
            $data['stoneshape']=Db::table('SET_StoneShape')->where('StoneShape_company_id', $companyId)->where('StoneShape_switch', 1)->select();

            return json([
                'code'=>200,
                'msg'=>'获取成功',
                'data'=>$data
            ]);

        }
        catch (Exception $e){
            return json(['code'=>-1,'msg'=>$e->getMessage()]);
        }

    }
    //查询进货单及明细
    public function Get_PurchaseBillInfo()
    {
        $userRoot = $this->request->auth['data']->user->user_root;
        $userId = $this->request->auth['data']->user->user_id;



        // 根据用户ID获取公司ID
        $companyId = Db::name('user')->where('user_id', $userId)->value('user_company_id');

        $current_page = Request::param('current_page');
        $page_size = Request::param('page_size');
        $begindate = Request::param('begindate'); // 开始日期
        $enddate = Request::param('enddate'); // 结束日期
        $billnumber = Request::param('billnumber'); // 订单号
        $state = Request::param('state');//状态
        $branchId=Request::param('branchId');//分店


        //判断是否是超级用户，如果是就把所有分公司查出来，不是就查该用户所属的分店
        if($userRoot==1){
            $branchs=Db::table('branch')->where('branch_company_id', $companyId)->column('branch_id');
        }else{
            $branchs=Db::table('vw_user_branch')->where('user_id', $userId)->column('branch_id');

        }



        // 构建查询条件
        $where = [];
        if ($begindate && $enddate) {
            // 设置开始日期的时分秒为00:00:00
            $startOfDay = date('Y-m-d 00:00:00', strtotime($begindate));
            // 设置结束日期的时分秒为23:59:59（或者你也可以选择结束日期的次日00:00:00来简化比较）
            $endOfDay = date('Y-m-d 23:59:59', strtotime($enddate));

            // 使用范围查询
            $where[] = ['PurchaseBill.PurchaseBill_creationtime', '>=', $startOfDay];
            $where[] = ['PurchaseBill.PurchaseBill_creationtime', '<=', $endOfDay];
        }
        if ($billnumber) {
            $where[] = ['PurchaseBill.PurchaseBill_BillNumber', 'like', '%' . $billnumber . '%'];

        }
        if ($companyId) {
            $where['PurchaseBill.PurchaseBill_company_id'] = $companyId;
        }
        if($state){
            $where['PurchaseBill.PurchaseBill_state'] = $state;
        }
        if($branchId){
            $where['PurchaseBill.PurchaseBill_branch_id'] = $branchId;
        }

        // 查询主表数据,按照PurchaseBill_creationtime时间字段排序
        $mainList = Db::table('vw_PurchaseBill')
            ->alias('PurchaseBill')
            ->whereIn('PurchaseBill_branch_id', $branchs)
            ->where($where)
            ->where('PurchaseBill_deleted',0)
            ->order('PurchaseBill_creationtime', 'desc')//按时间降序排名
            ->page($current_page, $page_size)
            ->select()->toarray();

        // 遍历主表数据，查询并附加明细表数据
        $data = [];
        foreach ($mainList as &$item) {
            // 查询对应的明细表数据
            $detailList = Db::table('vw_PurchaseDetailBill')
                ->where('PurchaseDetailBill_PurchaseBill_id', $item['PurchaseBill_id'])
                ->select();

            // 将明细表数据附加到主表数据上
            $item['detail'] = $detailList;
        }

        unset($item); // 取消引用，避免后续对$item的修改影响到$mainList


        // 获取总记录数
        $totalCount = Db::table('vw_PurchaseBill')
            ->alias('PurchaseBill')
            ->whereIn('PurchaseBill_branch_id', $branchs)
            ->where($where)
            ->where('PurchaseBill_deleted',0)
            ->order('PurchaseBill_creationtime', 'desc')//按时间降序排名
            ->count();

        // 返回JSON数据
        return json([
            'code' => 200, // 自定义状态码，0表示成功
            'msg' => '查询成功', // 自定义消息
            'data'=>[
                'data' => $mainList, // 主表数组包含明细表数组
                'total' => $totalCount, // 总数量

            ]

        ]);


    }

    //新增进货单
    public function Add_PurchaseBill()
    {
        $userId = $this->request->auth['data']->user->user_id;
        // 根据用户ID获取公司ID
        $companyId = Db::name('user')->where('user_id', $userId)->value('user_company_id');


        try {
            // 开启事务
            Db::startTrans();
            // 生成进货单号
            $purchaseBillNo = generateOrderNumber($companyId);

            // 获取请求中的进货单数据
            $purchaseBill= Request::param('purchaseBill');
            $PurchaseDetailBill= filterEmptyValues(Request::param('PurchaseDetailBill'));


            // 添加进货单主记录
//            $purchaseBill = [
//                'purchase_bill_no' => $purchaseBillNo, // 进货单号
//                // 其他进货单主表字段...
//            ];
            $purchaseBill['PurchaseBill_company_id'] = $companyId;
            $purchaseBill['PurchaseBill_BillNumber'] = $purchaseBillNo;
            $purchaseBill['PurchaseBill_state'] = '未确认';
            $purchaseBill['PurchaseBill_quantity'] =count(Request::param('PurchaseDetailBill'));
            $purchaseBill['PurchaseBill_user_id'] = $userId;

            $purchaseBillId = Db::table('PurchaseBill')->insertGetId($purchaseBill);
            if (!$purchaseBillId) {
                throw new \Exception('添加进货单主记录失败');
            }

            // 遍历货品明细并添加记录
            foreach ($PurchaseDetailBill as $detail) {
                // 生成条码（这里假设有一个generateBarcode函数）
                $barcode = generateBarcode($companyId);

                $DetailBill = $detail;
                $DetailBill['PurchaseDetailBill_Barcode'] = $barcode;
                $DetailBill['PurchaseDetailBill_company_id'] = $companyId;
                $DetailBill['PurchaseDetailBill_PurchaseBill_id'] = $purchaseBillId;
                $DetailBill['PurchaseDetailBill_branch_id'] = $purchaseBill['PurchaseBill_branch_id'];
                $result = Db::table('PurchaseDetailBill')->insert($DetailBill);
                if (!$result) {
                    throw new \Exception('添加进货单明细记录失败');
                }
            }

            // 提交事务
            Db::commit();

            // 添加成功，返回响应
            return json(['code' => '200', 'msg' => '进货单添加成功' ]);
        } catch (\Exception $e) {
            // 发生异常，回滚事务
            Db::rollback();

            // 返回错误信息
            return json(['code' => '402', 'msg' => $e->getMessage()]);


        }



    }

    //导入excl时检查基础资料
    public function checkImportData()
    {
        $userId = $this->request->auth['data']->user->user_id;
        // 根据用户ID获取公司ID
        $companyId = Db::name('user')->where('user_id', $userId)->value('user_company_id');

        $data = Request::post('data'); // 假设前端发送的是POST请求，且数据在'data'字段中，格式为JSON
        $missingData = []; // 用于存储缺失的基础数据的数组
        //$checkedItems = []; // 用于存储已检查过的项目，避免重复检查

        // 定义需要检查的字段及其对应的数据库表和方法
//        $fieldsToCheck = [
//            'PurchaseDetailBill_GoodsBrand_name' => 'SET_GoodsBrand',
//            'PurchaseDetailBill_GoodsSeries_name' => 'SET_GoodsSeries', // 假设存在这个表
//            'PurchaseDetailBill_GoodsCategory_name' => 'SET_GoodsCategory',
//            'PurchaseDetailBill_GoodsGrade_name' => 'SET_GoodsGrade',// 假设存在这个表
//            'PurchaseDetailBill_StoneInlay_name' => 'SET_StoneInlay', // 假设存在这个表
//            'PurchaseDetailBill_StoneShape_name' => 'SET_StoneShape', // 假设存在这个表
//            'PurchaseDetailBill_StoneColor_name' => 'SET_StoneColor', // 假设存在这个表
//            'PurchaseDetailBill_StoneClarity_name' => 'SET_StoneClarity', // 假设存在这个表
//            'PurchaseDetailBill_StoneCut_name' => 'SET_StoneCut', // 假设存在这个表
//            'PurchaseDetailBill_MainStoneCategory_name' => 'SET_StoneCategory', // 注意这个字段和下面的字段使用同一张表
//            'PurchaseDetailBill_AccessoryCategory_name' => 'SET_StoneCategory', // 注意这个字段使用同一张表，但可能是不同的字段
//        ];
        $fieldsToCheck = [
            '商品品牌' => 'SET_GoodsBrand',
            '商品系列' => 'SET_GoodsSeries', // 假设存在这个表
            '商品种类' => 'SET_GoodsCategory',
            '商品成色' => 'SET_GoodsGrade',// 假设存在这个表
            '宝石镶法' => 'SET_StoneInlay', // 假设存在这个表
            '宝石形状' => 'SET_StoneShape', // 假设存在这个表
            '宝石颜色' => 'SET_StoneColor', // 假设存在这个表
            '宝石净度' => 'SET_StoneClarity', // 假设存在这个表
            '宝石车工' => 'SET_StoneCut', // 假设存在这个表
            '主石类别' => 'SET_StoneCategory', // 注意这个字段和下面的字段使用同一张表
            '副石类别' => 'SET_StoneCategory', // 注意这个字段使用同一张表，但可能是不同的字段
        ];

        // 检查是否存在缺失数据的函数
        function checkMissingData($item, &$uniqueMissingData) {
            foreach ($uniqueMissingData as $existingItem) {
                if (isset($existingItem['field']) && isset($existingItem['value']) &&
                    $existingItem['field'] === $item['field'] && $existingItem['value'] === $item['value']) {
                    // 如果找到重复项，返回 true
                    return true;
                }
            }
            // 如果没有找到重复项，返回 false
            return false;
        }



        $uniqueMissingData = []; // 用于存储去重后的缺失数据
        $missingData = []; // 用于存储缺失的基础数据的数组



        foreach ($data as $item) {
            foreach ($fieldsToCheck as $field => $table) {
                if (isset($item[$field])) {
                    $value = $item[$field];
                        $exist = Db::table($table)->where(substr($table, strlen('SET_')).'_name', $value)->where(substr($table, strlen('SET_')).'_company_id',$companyId)->find();
                        if (!$exist) {
                            $missingData[] = ['field' => $field,'table' => $table, 'value' => $value];

                        }
                       // $checkedItems[] = $field;
                }
            }

        }
        // 检查是否已经添加过具有相同字段和值的项
//        if (!checkMissingData($missingData, $uniqueMissingData)) {
//            $uniqueMissingData[] = $missingData;
//        }

        //$uniqueMissingData = []; // 用于存储去重后的缺失数据
        // 去除 $missingData 中的重复项
        // 遍历$missingData数组
        foreach ($missingData as $item) {
            // 根据field、value和table生成唯一键
            $uniqueKey = $item['field'] . '_' . $item['value'] . '_' . $item['table'];

            // 检查唯一键是否已存在于$uniqueMissingData数组中
            $exists = false;
            foreach ($uniqueMissingData as $existingItem) {
                // 如果存在相同值的“石头类别”，则跳过当前项
                if ($existingItem['field'] === '石头类别' && $existingItem['value'] === $item['value']) {
                    $exists = true;
                    break;
                }
                // 检查是否已存在相同的唯一键（排除“石头类别”项）
                if ($existingItem['unique_key'] === $uniqueKey && $existingItem['field'] !== '石头类别') {
                    $exists = true;
                    break;
                }
            }

            // 如果当前项不存在于$uniqueMissingData数组中
            if (!$exists) {
                // 如果是“主石类别”或“副石类别”，则更改field为“石头类别”
                if ($item['field'] === '主石类别' || $item['field'] === '副石类别') {
                    $item['field'] = '石头类别';
                }

                // 添加 unique_key 到每个项中以用于去重
                $item['unique_key'] = $uniqueKey;

                // 将项添加到$uniqueMissingData数组中
                $uniqueMissingData[] = $item;
            }
        }

        // 去除 unique_key，如果不需要在结果中保留
        foreach ($uniqueMissingData as &$item) {
            unset($item['unique_key']);
        }

        return json(['code'=>200,'msg'=>'success','data' => $uniqueMissingData]);



    }

    //新增基础资料
    public function addBaseData(){

        $userId = $this->request->auth['data']->user->user_id;
        // 根据用户ID获取公司ID
        $companyId = Db::name('user')->where('user_id', $userId)->value('user_company_id');

        $data = Request::post('data'); // 假设前端发送的是POST请求，且数据在'data'字段中，格式为JSON

        // 开启事务
        Db::startTrans();
        try {
            foreach ($data as $item) {
                $tableName = $item['table'];
                $fieldName = str_replace('SET_', '', $tableName) . '_name';
                $fieldCompany= str_replace('SET_', '', $tableName) . '_company_id';
                $fieldSwitch = str_replace('SET_', '', $tableName) . '_switch';
                $fieldValue = $item['value'];

                // 检查字段是否已存在
                $isFieldExist = Db::table($tableName)->where($fieldName, $fieldValue)->where($fieldCompany,$companyId)->find();
                if (!$isFieldExist) {
                    // 字段不存在，则添加新记录
                    $result = Db::table($tableName)->insert([
                        $fieldName => $fieldValue,
                        $fieldCompany => $companyId,
                        $fieldSwitch => 1
                    ]);

                    if (!$result) {
                        throw new Exception('添加字段失败');
                    }
                }
            }

            // 提交事务
            Db::commit();

            // 返回成功信息
            return json(['code' => 200, 'msg' => '添加字段成功']);
        } catch (Exception $e) {
            // 发生错误，回滚事务
            Db::rollback();

            // 返回错误信息
            return json(['code' => 0, 'msg' => $e->getMessage()]);
        }


}

//根据前端传回的字段和值，找查相应的id,并返回
public function getIdByFieldAndValue(){
    $userId = $this->request->auth['data']->user->user_id;
    // 根据用户ID获取公司ID
    $companyId = Db::name('user')->where('user_id', $userId)->value('user_company_id');

    $data = Request::post('data'); // 假设前端发送的是POST请求，且数据在'data'字段中，格式为JSON

    $result = [];

    foreach ($data as $item) {
        $newItem = [];

        // 遍历每个字段
        foreach ($item as $key => $value) {
            if ($key === 'PurchaseDetailBill_name') {
                // PurchaseDetailBill_name 字段不需要处理，直接保留
                $newItem[$key] = $value;

            }  else if (strpos($key, '_name') !== false) {
                // 移除 PurchaseDetailBill_ 前缀和 _name 后缀，并替换为 SET_
                $dbName = str_replace(['PurchaseDetailBill_', '_name'], ['SET_', ''], $key);

                // 对于 MainStoneCategory 和 AccessoryCategory，使用特定的表名
                if (in_array($key, ['PurchaseDetailBill_MainStoneCategory_name', 'PurchaseDetailBill_AccessoryCategory_name'])) {
                    $dbName = 'SET_StoneCategory';
                }

                // 查询 ID
                $id = Db::table($dbName)->where(str_replace('SET_', '', $dbName) . '_name', $value)->where(str_replace('SET_', '', $dbName) . '_company_id', $companyId)->value(str_replace('SET_', '', $dbName) . '_id');

                // 如果没有找到 ID，则向前端返回 JSON 并终止处理
                if (!$id) {
                    return json(['code'=>201,'msg' => "ID not found for field: " . $key, 'data' => null], 201);
                }

                // 替换 _name 为 _id 并设置值
                $newItem[str_replace('_name', '_id', $key)] = $id;
            } else {
                // 不带 _name 的字段直接保留
                $newItem[$key] = $value;
            }
        }

        // 添加到结果数组中
        $result[] = $newItem;
    }

    // 返回处理后的数组给前端
    return json(['code'=>200,'data' => $result], 200);

}

//确认单据
public function confirmBill(){
    $userId = $this->request->auth['data']->user->user_id;
    // 根据用户ID获取公司ID
    $companyId = Db::name('user')->where('user_id', $userId)->value('user_company_id');

    Db::startTrans();
    try {
        $purchaseBillId =Request::param('PurchaseBill_id');

        // 获取该进货单下的所有商品明细
        $purchaseDetails = Db::table('PurchaseDetailBill')
            ->where('PurchaseDetailBill_PurchaseBill_id', $purchaseBillId)
            ->select();

        if (empty($purchaseDetails)) {
            throw new \Exception('进货单下无商品明细');
        }

        $productIdList = []; // 用于存储新插入商品的ID，以便于库存记录关联

        foreach ($purchaseDetails as $detail) {
            // 映射逻辑简化函数
            $mapFields = function ($prefixFrom, $prefixTo) use ($detail) {
                $data = [];
                foreach ($detail as $key => $value) {
                    if (strpos($key, $prefixFrom) === 0 && $key !== 'PurchaseDetailBill_PurchaseBill_id' && $key !== 'PurchaseDetailBill_branch_id' && $key !== 'PurchaseDetailBill_deleted') {
                        $newKey = str_replace($prefixFrom, $prefixTo, $key);
                        $data[$newKey] = $value;
                    }
                }
                return $data;
            };

            // 映射到product表
            $productData = $mapFields('PurchaseDetailBill_', 'product_');
            // 注意：需手动添加或调整没有规律可循的字段，比如关联公司等信息
            $productId = Db::table('product')->insertGetId($productData);

            if (!$productId) {
                throw new \Exception('商品信息插入失败');
            }

            $productIdList[] = $productId; // 记录新插入商品的ID

            // 映射到stock表
            $stockData = [
                'stock_product_id' => $productId,
                'stock_quantity' => 1,
                'stock_branch_id' => $detail['PurchaseDetailBill_branch_id'], // 假设这是从关联的PurchaseBill获取的
                'stock_company_id' => $companyId, // 同上
                // ... 其他stock表所需的字段映射
            ];
            $stockId = Db::table('stock')->insertGetId($stockData);

            if (!$stockId) {
                throw new \Exception('库存信息插入失败');
            }
        }

        // 更新PurchaseBill状态为已确认
        $updateResult = Db::table('PurchaseBill')
            ->where('PurchaseBill_id', $purchaseBillId)
            ->update(['PurchaseBill_state' => '已确认']);

        if (!$updateResult) {
            throw new \Exception('更新进货单状态失败');
        }


        Db::commit();
        return json(['code' => 200, 'msg' => '确认成功']);
    } catch (\Exception $e) {
        Db::rollback();
        return json(['code' => 500, 'msg' => $e->getMessage()]);
    }


}

//单据作废
public function invalidBill(){

    $userId = $this->request->auth['data']->user->user_id;
    // 根据用户ID获取公司ID
    $companyId = Db::name('user')->where('user_id', $userId)->value('user_company_id');

    Db::startTrans();
    try {
        $purchaseBillId =Request::param('PurchaseBill_id');

        //更新单据信息,状态改为作废
        $updateResult = Db::table('PurchaseBill')
            ->where('PurchaseBill_id', $purchaseBillId)
            ->update(['PurchaseBill_state' => '已作废']);

        if (!$updateResult) {
            throw new \Exception('更新进货单状态失败');
        }else{
            Db::commit();
            //返回更新成功信息
            return json(['code' => 200, 'msg' => '作废成功']);
        }

    } catch (\Exception $e) {
        Db::rollback();
        return json(['code' => 500, 'msg' => $e->getMessage()]);
    }



}

//删除进货单
public function deletePurchaseBill(){

    $userId = $this->request->auth['data']->user->user_id;
    // 根据用户ID获取公司ID
    $companyId = Db::name('user')->where('user_id', $userId)->value('user_company_id');

    Db::startTrans();
    try {
        // 获取前端传来的进货单ID
        $purchaseBillId = Request::param('PurchaseBill_id');

        // 更新PurchaseBill表中的deleted字段为1，实现逻辑删除
        $updateResultBill = Db::table('PurchaseBill')
            ->where('PurchaseBill_id', $purchaseBillId)
            ->update(['PurchaseBill_deleted' => 1]);

        if (!$updateResultBill) {
            throw new \Exception('进货单逻辑删除失败');
        }

        // 更新对应的PurchaseDetailBill表中的deleted字段为1，逻辑删除所有明细
        $updateResultDetail = Db::table('PurchaseDetailBill')
            ->where('PurchaseDetailBill_PurchaseBill_id', $purchaseBillId)
            ->update(['PurchaseDetailBill_deleted' => 1]);

        if (!$updateResultDetail) {
            throw new \Exception('进货单明细逻辑删除失败');
        }

        // 如果涉及到库存变动，这里可能还需要进一步处理库存表的状态

        // 提交事务
        Db::commit();

        return json(['code' => 200, 'msg' => '进货单及所有明细已逻辑删除']);
    } catch (\Exception $e) {
        // 事务回滚
        Db::rollback();
        return json(['code' => 500, 'msg' => $e->getMessage()]);
    }

}

//修改进货单主表
public function updatePurchaseBill(){

    $userId = $this->request->auth['data']->user->user_id;
    // 根据用户ID获取公司ID
    $companyId = Db::name('user')->where('user_id', $userId)->value('user_company_id');

    Db::startTrans();
    try {
        $purchaseBillId =Request::param('PurchaseBill_id');
        $data = Request::param('data');
        if(empty($data)){
            throw new \Exception('修改数据不能为空');
        }else{
            $updateResult = Db::table('PurchaseBill')
                ->where('PurchaseBill_id', $purchaseBillId)
                ->update($data);
            if (!$updateResult) {
                throw new \Exception('更新进货单信息失败');
            }else{
                Db::commit();
                //返回更新成功信息
                return json(['code' => 200,'msg' => '更新成功']);
            }
        }

    } catch (\Exception $e) {
        Db::rollback();
        return json(['code' => 500, 'msg' => $e->getMessage()]);
    }

}

//修改进货单明细表
public function updatePurchaseDetailBill(){
        $userId = $this->request->auth['data']->user->user_id;
        // 根据用户ID获取公司ID
        $companyId = Db::name('user')->where('user_id', $userId)->value('user_company_id');

        Db::startTrans();
        try {
            $purchaseDetailBillId =Request::param('PurchaseDetailBill_id');
            $data = Request::param('data');

            // 定义要忽略的字段列表
            $ignoredFields = [
                'PurchaseDetailBill_AccessoryCategory_name',
                'PurchaseDetailBill_Barcode',
                'PurchaseDetailBill_GoodsBrand_name',
                'PurchaseDetailBill_GoodsCategory_name',
                'PurchaseDetailBill_GoodsGrade_name',
                'PurchaseDetailBill_GoodsSeries_name',
                'PurchaseDetailBill_MainStoneCategory_name',
                'PurchaseDetailBill_StoneClarity_name',
                'PurchaseDetailBill_StoneColor_name',
                'PurchaseDetailBill_StoneCut_name',
                'PurchaseDetailBill_StoneInlay_name',
                'PurchaseDetailBill_StoneShape_name',
                'PurchaseDetailBill_branch_id',
                'PurchaseDetailBill_company_id',
                'PurchaseDetailBill_deleted',
                'PurchaseDetailBill_id',
            ];


            if(empty($data)){
                throw new \Exception('修改数据不能为空');
            }
            if(empty($purchaseDetailBillId)){
                throw new \Exception('进货单明细ID不能为空');
            }else{
                $data = array_diff_key($data, array_flip($ignoredFields));
                $updateResult = Db::table('PurchaseDetailBill')
                    ->where('PurchaseDetailBill_id', $purchaseDetailBillId)
                    ->update($data);
                if (!$updateResult) {
                    throw new \Exception('更新进货单明细信息失败');
                }else{

                    Db::commit();
                    //根据PurchaseDetailBill_id查询PurchaseBill_id,获取PurchaseBill_id,再根据PurchaseBill_id查询PurchaseDetailBill表中对应的数据
                    $PurchaseBill_id = Db::table('PurchaseDetailBill')
                        ->where('PurchaseDetailBill_id', $purchaseDetailBillId)
                        ->value('PurchaseDetailBill_PurchaseBill_id');
                    $PurchaseDetailBill = Db::table('vw_PurchaseDetailBill')
                        ->where('PurchaseDetailBill_PurchaseBill_id', $PurchaseBill_id)
                        ->select();
                    //返回更新成功信息
                }
            }
            return json(['code' => 200,'msg' => '更新成功','data'=>$PurchaseDetailBill]);

        } catch (\Exception $e) {
            Db::rollback();
            return json(['code' => 500, 'msg' => $e->getMessage()]);
        }
}

//删除进货单明细
public function deletePurchaseDetailBill(){
        $userId = $this->request->auth['data']->user->user_id;
        // 根据用户ID获取公司ID
        $companyId = Db::name('user')->where('user_id', $userId)->value('user_company_id');

        Db::startTrans();
        try {
            // 获取前端传来的进货单ID
            $purchaseDetailBillId = Request::param('PurchaseDetailBill_id');

           //获取到主表id
            $PurchaseBill_id = Db::table('PurchaseDetailBill')
                ->where('PurchaseDetailBill_id', $purchaseDetailBillId)
                ->value('PurchaseDetailBill_PurchaseBill_id');
            //根据主表id查询查询PurchaseBill中PurchaseBill_quantity字段如果值为1,则返回不允许删除
            $PurchaseBill_quantity = Db::table('PurchaseBill')
                ->where('PurchaseBill_id', $PurchaseBill_id)
                ->value('PurchaseBill_quantity');
            if($PurchaseBill_quantity == 1){
                return json(['code' => 500, 'msg' => '数量不足，不允许删除']);
            }

            // 直接删除PurchaseDetailBill表中数据
            $deleteResult = Db::table('PurchaseDetailBill')
                ->where('PurchaseDetailBill_id', $purchaseDetailBillId)
                ->delete();
            if (!$deleteResult) {
                throw new \Exception('删除进货单明细失败');
            }
            if($deleteResult){

                // 提交事务
                Db::commit();
                //根据PurchaseDetailBill_id查询PurchaseBill_id,获取PurchaseBill_id,再根据PurchaseBill_id查询PurchaseDetailBill表中对应的数据

                $PurchaseDetailBill = Db::table('vw_PurchaseDetailBill')
                    ->where('PurchaseDetailBill_PurchaseBill_id', $PurchaseBill_id)
                    ->select();
                //根据PurchaseBill_id查询PurchaseDetailBill表中对应的数据的总数
                $PurchaseDetailBillCount = Db::table('PurchaseDetailBill')
                    ->where('PurchaseDetailBill_PurchaseBill_id', $PurchaseBill_id)
                    ->count();
                //根据$PurchaseBill_id,更新PurchaseBill表中的PurchaseBill_quantity字段
                $updateResult = Db::table('PurchaseBill')
                    ->where('PurchaseBill_id', $PurchaseBill_id)
                    ->update(['PurchaseBill_quantity' => $PurchaseDetailBillCount]);
                //返回更新成功信息
                return json(['code' => 200, 'message' => '删除成功','data'=>$PurchaseDetailBill]);
            }

        } catch (\Exception $e) {
            // 事务回滚
            Db::rollback();
            return json(['code' => 500, 'msg' => $e->getMessage()]);

        }

}



}